package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CommentHotServiceImpl implements CommentHotService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void hotCommentExecutor(ApComment apComment) {
        log.info("异步计算热点文章==================> 开始");
        //查询，根据点赞排序
        Query query = Query.query(Criteria.where("entryId")
                .is(apComment.getEntryId()).and("flag").is(1))
                .with(Sort.by(Sort.Direction.DESC,"likes"));
        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);
        if(apCommentList == null || apCommentList.size() < 5){
            apComment.setFlag((short)1);
            mongoTemplate.save(apComment);
            return;
        }
        //获取最后一个热评，比较点赞数，多则替换
        ApComment lastHotComment = apCommentList.get(apCommentList.size()-1);
        if (apComment.getLikes()>lastHotComment.getLikes()) {
            // 当前评论改为热评
            apComment.setFlag((short)1);
            mongoTemplate.save(apComment);

            // 最后的评论改为普通评论
            lastHotComment.setFlag((short)0);
            mongoTemplate.save(lastHotComment);
        }
        log.info("异步计算热点文章==================> 结束");
    }
}